package cn.jtfadmin.base.dict.annotations.handle;

import cn.jtfadmin.base.dict.annotations.Dict;
import cn.jtfadmin.base.dict.service.DictService;
import cn.jtfadmin.base.lang.config.ApplicationHolder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;

public class DictSerializer extends StdSerializer<Object> implements ContextualSerializer {


    /**
     *
     */
    private static final long serialVersionUID = 1L;


    private static DictSerializer distance = new DictSerializer();

    public DictSerializer() {
        super(Object.class);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        return distance;
    }


    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (Objects.isNull(value)) {
            gen.writeNull();
            return;
        }
        String dictCode = null;
        String dictValue = null;
        String currentName = gen.getOutputContext().getCurrentName();
        if (value instanceof Enum) {
            Enum e = (Enum) value;
            gen.writeString(e.name());
            dictValue = e.name();
            dictCode = e.getClass().getSimpleName();
        } else {
            gen.writeString(String.valueOf(value));
            Class<?> aClass = gen.getOutputContext().getCurrentValue().getClass();
            Field field = FieldUtils.getField(aClass, currentName, true);
            Dict annotation = field.getAnnotation(Dict.class);
            dictCode = annotation.value();
            dictValue = String.valueOf(value);
        }


        DictService bean = ApplicationHolder.getApplicationContext().getBean(DictService.class);

        try {
            String dictText = bean.getDictText(dictCode, dictValue);
            gen.writeStringField(currentName + "_dictText", dictText);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }


}
